package com.cypher.encryptionanddecryption.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.cypher.encryptionanddecryption.R;
import com.cypher.encryptionanddecryption.bean.CommunicationBean;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.List;

/**
 *  通信列表适配器
 */
public class BaseAdapter<T> extends android.widget.BaseAdapter {

    private List<T> beans;
    /**
     * 上下文对象
     */
    private Context context;

    public List<T> get() {
        return beans;
    }

    public void set(List<T> beans) {
        this.beans = beans;
    }

    public BaseAdapter(Context context) {
        this.context = context;
    }

    @Override
    public int getCount() {
        return beans.size();
    }

    @Override
    public Object getItem(int position) {
        return beans.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    class ViewHolder {
        TextView name;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(
                    R.layout.fragment_communication_list_item, parent, false);
            viewHolder.name = convertView.findViewById(R.id.hex_name);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        T t = beans.get(position);
        String name = "";
        try {
            Field field = t.getClass().getDeclaredField("name");
            if (!field.isAccessible()) {
                field.setAccessible(true); // 取消Java语言监管
            }
            name = (String) field.get(t);
        } catch (IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();
        }
        viewHolder.name.setText(name);
        return convertView;
    }
}
